<?php

namespace Jammiest\SwigeCore\Servers;

use Jammiest\SwigeCore\Handlers\EventHandler;
use Jammiest\SwigeCore\Tools\Config;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputInterface;

class WebSocket extends Server
{

    public static function getInstance(array $config,ContainerInterface $container): \Swoole\WebSocket\Server
    {

        if (!self::$server) {
            
            /**
             * @var EventHandler
             */
            $eventHandler = null;
            $className = Config::get('server.event_handler.websocket',null);

            if ($className && class_exists($className)) {
                $eventHandler = new $className($container);
            } else {
                $eventHandler = new class($container) extends EventHandler {} ;
            }
            $server = new \Swoole\WebSocket\Server($config['host'], $config['port']);
            $server->set($config['settings']);

            if (isset($config['settings']['task_worker_num'])) {
                //处理异步任务(此回调函数在task进程中执行)。
                $server->on('Task', function ($serv, $task_id, $reactor_id, $data) use ($eventHandler) {
                    $eventHandler->onTask($serv, $task_id, $reactor_id, $data);
                });

                //处理异步任务的结果(此回调函数在worker进程中执行)。
                $server->on('Finish', function ($serv, $task_id, $data) use ($eventHandler) {
                    $eventHandler->onFinish($serv, $task_id, $data);
                });
            }

            $server->on('open', function (\Swoole\WebSocket\Server $server, $request) use ($eventHandler) {
                $eventHandler->onOpen($server, $request);
            });

            $server->on('message', function (\Swoole\WebSocket\Server $server, $frame) use ($eventHandler) {
                $eventHandler->onMessage($server, $frame);
            });

            $server->on('close', function ($server, $fd) use ($eventHandler) {
                $eventHandler->onClose($server, $fd);
            });
            $server->on('start', function ($server) use ($eventHandler) {
                $eventHandler->onStart($server);
            });

            $server->on('workerstart', function ($server,$workerId) use ($eventHandler) {
                $eventHandler->onWorkerStart($server,$workerId);
            });

            self::$server = $server;
        }
        return self::$server;
    }
}
